class Solution(object): def generate(self, root, result): if root: self.inorder(root.left, list) result.append(root.val) self.inorder(root.right, list) def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] result = [] self.generate(root, result) return result
迭代
和前序后序不同,需要遵循上面的思路
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Solution: # @param root, a tree node # @return a list of integers def inorderTraversal(self, root): result = [] stack = [] while root or stack: if root: stack.append(root) root = root.left else: root = stack.pop() result.append(root.val) root = root.right return result
递归(极简代码)
1 2 3 4 5 6 7 8 9 10
class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] else: return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)